package frame.log;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import frame.dao.DAO;
import frame.security.entity.AccessLog;
import frame.security.entity.User;

/**
 * frame 可选组件。用于记录系统的访问日志。
 * @author 崔鹏 2014-05-08
 *
 */
public class LogIntercptor extends HandlerInterceptorAdapter {

	@Autowired
	private DAO dao;
	@Autowired
	private HttpSession session;
	private User user;//当前登录系统的用户信息
	
	//因为退出系统时，shiro会将session中的用户信息清除掉。但是在这里，为了记录登出请求的
	//用户信息，需要在请求被controllor处理之前将其中的用户信息获取到。
	//方便在下面的afterCompletion方法中使用。
	//
	public void postHandle(HttpServletRequest request,  
	        HttpServletResponse response, Object handler,  
	        ModelAndView modelAndView) throws Exception {  
		if(user==null){
			user=(User)session.getAttribute("current_user");
		}
	}
	
	//这个日志记录工具选择使用afterCompletion来做是应为这个方法可以获取到异常信息。
	@SuppressWarnings("rawtypes")
	public void afterCompletion(HttpServletRequest request,  
	        HttpServletResponse response, Object handler, Exception ex)  
	        throws Exception {  
			
			AccessLog log=new AccessLog();
			log.setUrl(request.getRequestURI());
			
			log.setUser_id(user.getUser_id());
			log.setUser_name(user.getUser_name());
			
			String[] order={"url","user_id","user_name","paramin","descp"};
			Enumeration  pnames=request.getParameterNames();
			StringBuilder strb=new StringBuilder(32);
			while(pnames.hasMoreElements()){
				String name=(String)pnames.nextElement();
				strb.append(name).append("=").append(request.getParameter(name)).append(";");
			}
			log.setParamin(strb.toString());
			if(ex ==null){
				log.setDescp("success");
			}else{
				log.setDescp(ex.getMessage());
			}
			dao.updateObject("addLog", log,order);
	}

}
